package com.mingqijia.gassafety.shared.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
@Configuration
public class AutoFillConfig implements MetaObjectHandler {

    //自动维护创建时间+更新时间
    static final String CREATE_TIME = "createdAt";
    static final String UPDATE_TIME = "updatedAt";
    static final String IS_DELETED = "isDeleted";
    @Override
    public void insertFill(MetaObject metaObject) {
        Date date = new Date();
        Object createDate = getFieldValByName(CREATE_TIME, metaObject);
        if (createDate != null){
            date =(Date) createDate;
        }
        // 看实体类中是否有这个属性，有的话就执行。没有就不执行
        boolean hasSetter = metaObject.hasSetter(CREATE_TIME);
        if (hasSetter) {
            setInsertFieldValByName(CREATE_TIME, date, metaObject);
            setInsertFieldValByName(UPDATE_TIME, new Date(), metaObject);
            setInsertFieldValByName(IS_DELETED, 0, metaObject);
        }

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        // 如果预先自己设置了值，则设置不使用MP的自动填充
        Object val = getFieldValByName(UPDATE_TIME, metaObject);
        if (val == null) {
            setUpdateFieldValByName(UPDATE_TIME, new Date(), metaObject);
        }
    }

}
